到了今天,我想讓遊戲開始有比較完整的架構。我請 AI 加入玩家的道具,以及使用 class 建立角色。這一天會一次看到前面學習的陣列、for 迴圈、class、方法。
using System;
class Character
{
public string name;
public int health;
public Character(string name, int health)
{
this.name = name;
this.health = health;
}
public void ShowStatus()
{
Console.WriteLine(name + " 的生命值:" + health);
}
}
class Program
{
static void Main()
{
Character player = new Character("玩家", 100);
string[] items = { "生命藥水", "魔法石", "寶箱鑰匙" };
player.ShowStatus();
Console.WriteLine("你的道具:");
for (int i = 0; i < items.Length; i++)
{
Console.WriteLine((i + 1) + ". " + items[i]);
}
}
}
class Character
建立一個 Character 類別,可以把它想成角色的設計圖
public string name;
public int health;
角色具有名稱與生命值。
public Character(string name, int health)
這是建構子,可以在建立角色時直接設定資料。
Character player = new Character("玩家", 100);
利用 Character 建立一個玩家物件。
string[] items
建立一個字串陣列,用來存放多個道具。
for (int i = 0; i < items.Length; i++)
利用 for 迴圈逐一讀取陣列中的道具。
items[i]
取得陣列中第 i 個位置的資料。
今天讓我比較明顯感受到 class 的用途。如果遊戲裡有很多角色,直接使用大量變數會非常混亂。使用 class 後,就可以把角色相關的資料與功能整理在一起。而陣列則適合管理大量相同類型的資料。這些之前看起來分開的 C# 知識,開始慢慢連在一起了。